package com.hzchendou.blog.demo.gateway.security.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hzchendou.blog.demo.common.model.vo.ResultVO;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;

@Slf4j
@Component
public class LoginLoseHandler extends HttpBasicServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        ResultVO<String> resultVO = ResultVO.fail("登录失效");
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        Mono<Void> ret = null;
        try {
            ret = response.writeAndFlushWith(
                        Flux.just(ByteBufFlux.just(response.bufferFactory().wrap(resultVO.toJson().getBytes(
                                StandardCharsets.UTF_8)))));
        } catch (JsonProcessingException ex) {
            log.error("登录失败处理异常", ex);

        }
        return ret;
    }
}